// pages/addContact/addContact.js

import {
  PATHS_ALIAS, SERVERS_INFO, SERVERS_ALIAS
} from '../../utils/api.js';
import {
  http
} from '../../utils/network.js';
import utils from '../../utils/util.js'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageType: 'add', //页面用途   edit add(默认) addFirst(添加第一个联系人)
    activityId: '', //活动Id
    ticketId: '', //票种Id
    unionId:'',
    headImgUrl:'',
    userId: '', //用户id
    contactId: '', //要编辑的联系人ID
    formData: {}, //表单
    formDataOld:{},   //表单旧数据--填入
    ticketInfo: {}, //票种信息
    ticketInfoBase: [], //报名元素--基本信息
    ticketInfoEmergency: [], //报名元素--紧急联系信息
    ticketInfoOther: [], //报名元素--其他信息
    hasIcCartItem:'',   //有没有身份证表单
    hasOldIdCard:false,     //数据库有身份证信息，则年龄和性别只读
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //console.log(options);
    this.setData({
      userId:wx.getStorageSync('userId'),
      unionId: wx.getStorageSync('unionId'),
      headImgUrl: wx.getStorageSync('userInfo').avatarUrl,
      pageType: options.pageType ? options.pageType : 'add',
      contactId: options.contactId ? options.contactId : '',
      ticketId: options.ticketId ? options.ticketId : '',
      activityId: options.activityId ? options.activityId : '',


      // pageType:'edit',
      // contactId:322,
      // activityId:805,
      // ticketId:1098,
    });
    this.getTicketInfo();

  },
  // 删除
  del: function() {
    let _this = this;
    wx.showModal({
      title: '提示',
      content: '是否确认删除？',
      showCancel: true,
      cancelText: '取消',
      cancelColor: '#F45450',
      confirmText: '确定',
      confirmColor: '#F45450',
      success: function (data) {
        if (data.confirm) {
          let params = {
            id: _this.data.contactId
          }
          http({
            path: PATHS_ALIAS.DELETE_CONTACTS,
            params: params,
            success: function (res) {
              //console.log(res);
              wx.showToast({
                title: '删除成功！',
                icon: 'none'
              });
              wx.navigateBack({
                delta: 1
              })
            },
            fail: function (err) {
              //console.log(err);
              wx.showToast({
                title: '删除失败',
                icon: 'none'
              });
            }
          })
        } else if (data.cancel) {
          
        }
      }
    }) 
  },
  // 保存
  save: utils.throttle(function (e) {
    let _this = this;
    if (!this.checkForm()) {
      return;
    };

    let path = '';
    let pageType = this.data.pageType;
    let params = this.data.formData;
    params.unionId = this.data.unionId;
    params.headImgUrl = this.data.headImgUrl;
    if (pageType == 'add' || pageType == 'addFirst') {   //添加联系人
      path = PATHS_ALIAS.ADD_CONTACTS;
      params.userId = _this.data.userId;
    } else if (pageType == 'edit'){   //编辑联系人
      path = PATHS_ALIAS.UPDATE_CONTACTS;
      params.userId = _this.data.userId;
      params.id = _this.data.contactId;
    };

    //console.log();
    http({
      path:path,
      params: params,
      success:function(res){
        //console.log(res);
        if(res.code == 0){
          wx.navigateBack({
            delta: 1
          })
        }
      },
      fail:function(err){
        //console.log(err)
      }
    })
  },3000),
  //校验表单
  checkForm: function() {
    let formData = this.data.formData;
    let ticketInfoBase = this.data.ticketInfoBase;
    let ticketInfoEmergency = this.data.ticketInfoEmergency;
    let ticketInfoOther = this.data.ticketInfoOther;
    let ticketInfoAll = ticketInfoBase.concat(ticketInfoEmergency, ticketInfoOther);

    // 正则规则
    let isNameReg = /^[\u4E00-\u9FA5A-Za-z]{2,15}$/;
    let isCodeIdReg = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;
    let isMobileReg = /^0?1[3-9|4|5|7|8|9][0-9]\d{8}$/;

    // 校验基本信息
    for (let i = 0; i < ticketInfoAll.length; i++) {
      let item = ticketInfoAll[i];
      let name = item.actElementName;
      let key = item.actElementCode;
      let val = formData[key];
      if (val == '') {
        let title = '请输入' + name;
        if (key == 'imgUrl'){
          title = '请上传' + name;
        };
        wx.showToast({
          title: title,
          icon: 'none'
        });
        return false;
      };
      if (key == 'entryName' || key == 'emergencyName') { //姓名校验
        if (!isNameReg.test(val)) {
          wx.showToast({
            title: name + '输入不合法',
            icon: 'none'
          });
          return false;
        }
      } else if (key == 'entryMobile' || key == 'emergencyMobile') { //手机号码校验
        if (!isMobileReg.test(val)) {
          wx.showToast({
            title: name + '输入不合法',
            icon: 'none'
          });
          return false;
        }
      } else if (key == 'entryIdNumber') { //身份证号校验
        if (!isCodeIdReg.test(val)) {
          wx.showToast({
            title: name + '输入不合法',
            icon: 'none'
          });
          return false;
        }
      };
    };
    return true;
  },
  // 获取票种信息，
  getTicketInfo: function() {
    let _this = this;
    let params = {
      activityId: this.data.activityId, //	活动ID	number	必填
      ticketId: this.data.ticketId, //	票种ID	number	必填
    };
    http({
      path: PATHS_ALIAS.GET_TICKET_INFO,
      params: params,
      success: function(res) {
        //console.log(res)
        _this.setData({
          ticketInfo: res.response.ticketInfo
        });
        _this.filterTicketInfo();
      },
      fail: function(err) {
        //console.log(err)
      }
    })
  },
  // 过滤出报名报名元素
  filterTicketInfo() {
    let actElementList = this.data.ticketInfo.actElementList;
    let ticketInfoBase = [];
    let ticketInfoEmergency = [];
    let ticketInfoOther = [];
    let formData = {};

    // 判断是否有身份证元素
    let hasIcCartItem = actElementList.find(function(item){
      return item.actElementCode == 'entryIdNumber'
    });
    // 表单信息分类
    actElementList.forEach(function(item, index) {
      if (item.elementType == 'base') {
        ticketInfoBase.push(item);
        formData[item.actElementCode] = '';
      } else if (item.elementType == 'emergency') {
        ticketInfoEmergency.push(item);
        formData[item.actElementCode] = '';
      } else if (item.elementType == 'other') {
        //有身份证号时，省略填写性别、年龄
        if (hasIcCartItem && (item.actElementCode == 'entryAge' || item.actElementCode == 'entrySex')) {
          // //console.log(111111111111)
        }else{
          ticketInfoOther.push(item);
          formData[item.actElementCode] = '';
        }
      };
    });
    
    this.setData({
      ticketInfoBase,
      ticketInfoEmergency,
      ticketInfoOther,
      formData,
      hasIcCartItem: hasIcCartItem?true:false
    });
    if (this.data.pageType == 'addFirst') { //添加第一个联系人--自动填入用户信息
      this.getUserInfo();
    } else if (this.data.pageType == 'edit'){
      this.getContactInfo();
    };
  },
  // 获取用户信息
  getUserInfo: function() {
    let _this = this;
    let params = {
      relUserId: this.data.userId,
    };
    http({
      path: PATHS_ALIAS.GET_USER_INFO,
      params: params,
      success: function(res) {
        // //console.log(res.response)
        _this.setFormData(res.response, 'userInfo');
      },
      fail: function(err) {
        //console.log(err)
      }
    })
  },
  // 获取联系人数据--编辑时用
  getContactInfo: function () {
    let _this = this;
    let params = {
      id: this.data.contactId,
    };
    http({
      path: PATHS_ALIAS.VIEW_CONTACTS,
      params: params,
      success: function (res) {
        //console.log(res.response)
        _this.setFormData(res.response, 'contact');
      },
      fail: function (err) {
        //console.log(err)
      }
    });
  },
  // 填入旧数据  dataType:userInfo(用户数据)  contact(联系人数据)
  setFormData: function(oldData, dataType) {
    let _this = this;
    let formData = this.data.formData;
    let formDataOld = this.data.formData;
    let actElementList = this.data.ticketInfo.actElementList;   //所有表单对象数组
    // let ticketInfoAll = ticketInfoBase.concat(ticketInfoEmergency, ticketInfoOther);

    if (dataType == 'userInfo') {
      // 统一字段名称
      oldData.entryName = oldData.name;
      oldData.entryMobile = oldData.mobile;
      oldData.entryIdNumber = oldData.idNo;
      oldData.entrySex = oldData.sex;
      oldData.entryAge = oldData.age;
    } else if (dataType == 'contact'){
      //判断数据库有没有身份证数据
      if (oldData.entryIdNumber) {
        this.setData({
          hasOldIdCard: true
        })
      };
    };
    actElementList.forEach(function (item, index) {
      let key = item.actElementCode;
      formData[key] = oldData[key];
      formDataOld[key] = oldData[key];
    });
    this.setData({
      formData,
      formDataOld
    });
  },

  // 图片上传
  picUpload: function() {
    let _this = this;
    wx.chooseImage({
      count: 1, //最多可以选择的图片张数
      sizeType: ['original', 'compressed'], //所选的图片的尺寸
      success(res) {
        //console.log(res);
        let size = res.tempFiles["0"].size;
        if (size > 8 * 1024 * 1024) { //大小超限
          wx.showToast({
            title: '选择图片的大小请在8M以内',
            icon: 'none'
          })
          return;
        };
        const tempFilePaths = res.tempFilePaths
        let host = SERVERS_INFO[SERVERS_ALIAS.MAIN].host;
        wx.showLoading({
          title: '上传中...',
        });
        wx.uploadFile({
          url: host+'/user/entryImageUpload.ext', //接口地址
          filePath: tempFilePaths[0],
          header: {
            'token': 11,
            'Content-Type': 'application/json;charset=UTF-8',
            'appId': "com.smk.test.test"
          },
          name: 'imageFile',
          // formData: {
          //   'user': 'test'
          // },
          success(res) {
            //console.log(res);
            wx.hideLoading();
            let formData = _this.data.formData;
            let result = JSON.parse(res.data).response;
            let picReviewSrc = result.fileRdfUrl + result.url;
            formData.imgUrl = picReviewSrc;
            _this.setData({
              formData
            })
          },
          fail(err) {
            //console.log(err);
          }
        })
      }
    })

  },
  // 删除图片
  delPicUpload: function() {
    let formData = this.data.formData;
    formData.imgUrl = '';
    this.setData({
      formData
    })
  },
  // 预览图片
  picReview: function(e) {
    wx.previewImage({
      urls: [e.currentTarget.dataset.src],
    })
  },
  // 输入监听--通用
  inputWacth: function(e) {
    //console.log(e);
    let formData = this.data.formData;
    let item = e.currentTarget.dataset.model;
    let key = 'formData.' + item;
    this.setData({
      [key]: e.detail.value
    });
  },

  // 性别单选框改变
  sexChange: function(e) {
    // //console.log(e);
    let formData = this.data.formData;
    formData[e.currentTarget.dataset.model] = e.currentTarget.dataset.val;
    this.setData({
      formData
    });
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})